package com.example.beat_x3.Fragments;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.ImageDecoder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;

import com.example.beat_x3.Client.GetResult;
import com.example.beat_x3.Client.LoadImages;

import com.example.beat_x3.R;

import java.io.IOException;
import java.util.UUID;

import Entity.Equipment;
import Entity.Inf;

public class ChujieFragment extends MyFragment {
    public EditText instrument_detail, instrument_name, instrument_span;
    public ImageView shuchu;
    public Button select, upload;
    public ImageView back;

    private static int UPLOAD_IMAGE_STATUS = 0;

    private static String selectedImagePath;
    public boolean isUpload = false;
    private static ActivityResultLauncher<String> imagePickerLauncher;
    public Handler myHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                Toast.makeText(Inf.context, "上传成功", Toast.LENGTH_SHORT).show();
            }
        }
    };

    @SuppressLint("SimpleDateFormat")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        @SuppressLint("InflateParams") View view = inflater.inflate(R.layout.fragment_chujie, null);
        imagePickerLauncher = registerForActivityResult(
                new ActivityResultContracts.GetContent(),
                result -> {
                    if (result != null) {
                        handleImageResult(result);
                    } else {
                        Toast.makeText(Inf.context, "未选择图片", Toast.LENGTH_SHORT).show();
                    }
                }
        );
        instrument_detail = view.findViewById(R.id.chujie_detail);
        instrument_name = view.findViewById(R.id.chujie_instrument_name);
        instrument_span = view.findViewById(R.id.chujie_instrument_span);
        select = view.findViewById(R.id.chujie_select);
        shuchu = view.findViewById(R.id.picture_instrument);
        upload = view.findViewById(R.id.button2);
        back = view.findViewById(R.id.chujie_backbutton);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                changeFragment(Inf.instrumentFragment);
                if (isUpload) {
                    Inf.instrumentFragment.instrumentAdapter.appendNew();
                    Inf.instrumentFragment.isUpload = true;
                    isUpload = false;
                }
            }
        });
        select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openImagePicker();
            }
        });
        upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (UPLOAD_IMAGE_STATUS == 1) {
                    String name = instrument_name.getText().toString().trim();
                    String detail = instrument_detail.getText().toString().trim();
                    String image = selectedImagePath.substring(selectedImagePath.lastIndexOf('/') + 1);
                    String span = instrument_span.getText().toString().trim();
                    if (name.length() != 0 && detail.length() != 0 && span.length() != 0&&name.length()<=30&&detail.length()<=100) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                LoadImages.upLoadImage(selectedImagePath, LoadImages.EQUIPMENT_IMAGES);
                                if (GetResult.AddNewEquipmentGR(name, Inf.stuInf.StudentAccount, image, span, detail) == 1) {
                                    isUpload = true;
                                    Equipment n = new Equipment("-1", name, Inf.stuInf.StudentAccount, image, 1, Integer.parseInt(span), "上架乐器重登后完全显示");
                                    Inf.instrumentFragment.instrumentAdapter.equipments.add(n);
                                    if (Inf.myinstrumentFragment != null) {
                                        if (Inf.myinstrumentFragment.myInstrumentAdapter.equipments != null) {
                                            Inf.myinstrumentFragment.myInstrumentAdapter.equipments.add(n);
                                        }
                                    }
                                    myHandler.sendEmptyMessage(0);
                                }
                            }
                        }).start();
                    }
                }
            }
        });
        return view;
    }

    private void openImagePicker() {
        imagePickerLauncher.launch("image/*");
    }

    private void handleImageResult(Uri imageUri) {
        try {
            UPLOAD_IMAGE_STATUS = 0;
            ImageDecoder.Source source = ImageDecoder.createSource(Inf.context.getContentResolver(), imageUri);
            Bitmap bitmap = ImageDecoder.decodeBitmap(source);
            shuchu.setImageBitmap(bitmap);
            String uName = UUID.randomUUID().toString() + ".png";
            new Thread(new Runnable() {
                @Override
                public void run() {
                    selectedImagePath = LoadImages.saveBitmapToInternalStorage(bitmap, uName);
                    UPLOAD_IMAGE_STATUS = 1;
                }
            }).start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
